from datetime import datetime,timedelta

import jwt
from flask import current_app
from jwt import PyJWTError

from comment.modules.user import User
from comment.utils import const


def generate_tokens(uid):
    """
    一个用户再一次会话中生成一个token
    :param uid:
    :return:
    """
    params={
        'id':uid,
        'exp':datetime.utcnow()+timedelta(seconds=const.JWT_EXPIRY_SECOND)
    }

    return jwt.encode(payload=params,key=const.SECRET_KEY,algorithm='HS256')

def verify_tokens(token_str):
    """
    验证token,验证成功，返回用户ID
    :param token_str:
    :return:
    """
    try:
        # 返回之前生产token的时候的字典
        data = jwt.decode(token_str, key=const.SECRET_KEY, algorithms='HS256')
        current_app.logger.info(data)
        user = User.query.filter(User.id == data['id']).first()
        if user and user.onlock == 0:  # 当前用户的状态正常
            return {'id': user.id}
        else:
            return {'message': '数据库中不存在当前用户，或者用户已经过期'}
    except PyJWTError as e:
        current_app.logger.error(e)
        return {'message': 'token 验证识别'}